package com.example.recruit.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.recruit.common.R;
import com.example.recruit.dto.EmployerCompany;
import com.example.recruit.entity.Company;
import com.example.recruit.entity.Employer;
import com.example.recruit.entity.User;
import com.example.recruit.mapper.CompanyMapper;
import com.example.recruit.mapper.EmployerMapper;
import com.example.recruit.service.CompanyService;
import com.example.recruit.service.EmployerService;
import com.example.recruit.service.UserService;
import com.example.recruit.util.BaseThreadLocal;
import com.example.recruit.util.IsEmployer;
import com.example.recruit.util.RegxPhoneNumber;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HR类
 * login 登录
 * getCode 获取验证码
 * register 注册
 * searchAll 查询雇主所属公司数据
 * getUserById 通过id查询用户
 *getList返回所有公司数据
 * @author wei
 */
@Slf4j
@RestController
@RequestMapping("/employer")
@CrossOrigin(origins = "*")
public class EmployerController {
    @Autowired
    private EmployerService employerService;

    @Autowired
    private EmployerMapper employerMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyMapper companyMapper;




    @GetMapping("/getList")
    public R<List<Company>> getCompanyList(){
        List<Company> companyList = companyMapper.getCompanyList();
        return R.success(companyList);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public R<Employer> login(@RequestBody Map map, HttpServletRequest request){

        String phone=(String) map.get("phone");
        String password = (String) map.get("password");
       // String code=(String) map.get("code");
        log.info("login,电话号码:"+phone);
        if(!RegxPhoneNumber.regxPhone(phone)){
            return R.error("请输入正确的手机号");
        }
//        HttpSession session = request.getSession();
//        log.info("login:session"+session.getId());
//
//        String vertifyCode= (String) session.getAttribute(phone);
        if(true){
            LambdaUpdateWrapper<Employer> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(Employer::getPhone,phone).eq(Employer::getPassword,password);
            Employer employerOne = employerService.getOne(lambdaUpdateWrapper);
            if(employerOne!=null){
                employerOne.setPassword("");
                request.getSession().setAttribute("employee",employerOne.getId());
                BaseThreadLocal.setThreadLocalId(employerOne.getId());
                return R.success(employerOne);
            }
        }else {
            R.error("验证码错误");
        }
        return R.error("账号或密码错误");
    }
    /**
     * 图片验证码
     */
    @GetMapping("/getCode")
    public R<String> getCode( String phone, HttpServletRequest request, HttpServletResponse response){
        if(phone==null){
            return R.error("请输入手机号");
        }
        log.info("电话号码"+phone);
        if(!RegxPhoneNumber.regxPhone(phone)){
            return R.error("请输入正确的手机号");
        }
        HttpSession session = request.getSession();
        log.info("sessionID:"+session.getId());
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        try {
            captcha.write(response.getOutputStream());
            String code = captcha.getCode();
            session.setAttribute(phone,code);
            log.info("验证码："+code);
            log.info("session:"+session.getId());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success("验证码获取成功");
    }

    /**
     * 注册
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody Map map, HttpServletRequest request){
        String phone=(String) map.get("phone");
        String password=(String) map.get("password");
        String passwordAgain= (String) map.get("passwordAgain");
        String name= (String) map.get("name");
        String companyId= (String) map.get("companyId");

       // String code= (String) map.get("code");
        if(!RegxPhoneNumber.regxPhone(phone)){
            return R.error("请输入正确的手机号");
        }
//        HttpSession session = request.getSession();
//        String vertifyCode = (String) session.getAttribute(phone);
        if(true){
            Employer employer=new Employer();
            employer.setPhone(phone);
            employer.setPassword(password);
            employer.setBossName(name);
            employer.setCompanyId(companyId);
            if(employer!=null&&employer.getPassword()!=null&&employer.getPhone()!=null){
                employerService.save(employer);
                return R.success("注册成功");
            }
        }
        return R.error("注册失败");
    }

    /**
     * 雇主和公司的数据
     * @return
     */
    @GetMapping("/searchAll")
    public R<List<EmployerCompany>> searchAll(String id){
        List<EmployerCompany> employerCompanyList =new ArrayList<>();
        log.info("id:"+id);
        if(id==null){
          employerCompanyList = employerMapper.getEmployerAllList();
            return R.success(employerCompanyList);
        }else {
            EmployerCompany employerCompany = employerMapper.getEmployerAllById(id);
            employerCompanyList.add(employerCompany);
            return R.success(employerCompanyList);
        }

    }

    /**
     * 修改信息
     * @param employer
     * @return
     */
    @PostMapping("/modifyEmployer")
    public R<String> modifyEmploy(@RequestBody Employer employer){
        if(employer.getId()!=null&&employer!=null){
            employerService.updateById(employer);
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 通过id查询user
     * @param user
     * @return
     */
    @PostMapping("/getUser")
    public R<User> getUserById(@RequestBody User user){
        if(user!=null){
            User userOne = userService.getById(user.getId());
            if(userOne!=null){
                userOne.setPassword("");
                return R.success(userOne);
            }

        }
        return R.error(null);
    }
    /**
     * 修改密码
     * @return
     */
    @PostMapping("/changePassword")
    public R<String> updatePassword(@RequestBody Map map){
        long EmpId= Long.parseLong((String) map.get("EmpId"));
        String oldPassword= (String) map.get("oldPassword");
        LambdaQueryWrapper<Employer> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employer::getId,EmpId).eq(Employer::getPassword,oldPassword);
        Employer employerOne = employerService.getOne(lambdaQueryWrapper);
        if(employerOne!=null){
            String newPassword= (String) map.get("newPassword");
            String newPasswordAgain= (String) map.get("newPasswordAgain");
            if(!(newPassword.trim().equals("")&&newPasswordAgain.trim().equals(""))){
                if(newPassword.equals(newPasswordAgain)){
                    employerOne.setPassword(newPassword);
                    boolean flag = employerService.updateById(employerOne);
                    if(flag){
                        return R.success("修改成功");
                    }
                }
            }
        }
        return R.error("修改失败");

    }
}
